package com.example.booksystem.action;

import com.alibaba.fastjson.JSON;
import com.example.booksystem.bean.Book;
import com.example.booksystem.bean.Record;
import com.example.booksystem.biz.BookBiz;
import com.example.booksystem.dao.RecordDao;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/book")
public class BookServlet extends HttpServlet {
    BookBiz bookBiz = new BookBiz();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取对象
        PrintWriter out = resp.getWriter();
        String type = req.getParameter("type");
        switch (type){
            case "add":
                try {
                    add(req,resp,out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "modifypre":
                long bookId = Long.parseLong(req.getParameter("id"));
                Book book = bookBiz.getById(bookId);
                req.setAttribute("book",book);
                req.getRequestDispatcher("book_modify.jsp").forward(req,resp);
                break;
            case "modify":
                try {
                    modify(req,resp,out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "remove":
                long removeId = Long.parseLong(req.getParameter("id"));
                try {
                    int count =  bookBiz.remove(removeId);
                    if(count>0){
                        out.println("<script>alert('图书删除成功'); location.href='book?type=query&page=1';</script>");
                    }else{
                        out.println("<script>alert('图书删除失败'); location.href='book?type=query&page=1';</script>");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    out.println("<script>alert('"+e.getMessage()+"'); location.href='book?type=query&page=1';</script>");
                }
                //3. 提示+跳转=>out (查询的servlet)
                break;
            case "query":
                query(req,resp,out);
                break;
            case "details":
                details(req,resp,out);
                break;
            case "doajax":
                String name = req.getParameter("name");
                Book book2 = bookBiz.getByName(name);
                if(book2==null){
                    out.print("{}");//null json 对象
                }else{
                    out.print(JSON.toJSONString(book2));
                }
                break;
        }

    }

    private void add(HttpServletRequest request,HttpServletResponse response,PrintWriter out) throws Exception {
        //构建磁盘工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024*9);
        //临时仓库
        File file = new File("e:\\temporary");
        if (!file.exists()){
            file.mkdir();
        }
        factory.setRepository(file);
        //文件+表单
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //请求解析成一个个FileItem(文件+表单)
        List<FileItem> fileItems = fileUpload.parseRequest(request);
        Book book = new Book();
        for (FileItem fileItem : fileItems){
            //判断是文件还是表单元素
            if (fileItem.isFormField()){
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");//防止乱码
                switch(name){
                    case "typeId":
                        book.setTypeId(Long.parseLong(value));
                        break;
                    case "name":
                        book.setName(value);
                        break;
                    case "price":
                        book.setPrice(Float.parseFloat(value));
                        break;
                    case "desc":
                        book.setDesc(value);
                        break;
                    case "publish":
                        book.setPublish(value);
                        break;
                    case "author":
                        book.setAuthor(value);
                        break;
                    case "stock":
                        book.setStock(Long.parseLong(value));
                        break;
                    case "address":
                        book.setAddress(value);
                        break;
                }
            }else {
                //图片名
                String fileName = fileItem.getName();
                //保存到
                String path = request.getServletContext().getRealPath("/Images/cover");
                String filePath = path+"/"+fileName;
                //数据库表中的路径 ：Images/cover/101-1.png：相对项目的根目录的位置
                String dbPath  = "Images/cover/"+fileName;
                book.setPic(dbPath);
                //4.3 保存文件
                fileItem.write(new File(filePath));
            }
        }
        //保存到数据库
        int count = bookBiz.add(book.getTypeId(),book.getName(),book.getPrice(),book.getDesc(),book.getPic(),book.getPublish(),book.getAuthor(),book.getStock(),book.getAddress());
        if(count>0){
            out.println("<script>alert('添加书籍成功');location.href='book?type=query&page=1';</script>");
        }else{
            out.println("<script>alert('添加书籍失败');location.href='book_add.jsp';</script>");
        }

    }

    private void query(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //1.获取信息(页数，页码,信息)
        int pageSize = 3;
        int pageCount = bookBiz.getPageCount( pageSize);
        int pageIndex = Integer.parseInt(req.getParameter("page"));
        if(pageIndex<1){
            pageIndex = 1;
        }
        if(pageIndex>pageCount){
            pageIndex = pageCount;
        }
        List<Book> books = bookBiz.getByPage(pageIndex,pageSize);

        //2.存

        req.setAttribute("pageCount",pageCount);
        req.setAttribute("books",books);

        //3. 转发到jsp页面
        req.getRequestDispatcher("book_list.jsp?page="+pageIndex).forward(req,resp);
    }

    private void details(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //1.获取图书的编号
        long bookId =  Long.parseLong(req.getParameter("id"));
        //2.根据编号获取图书对象
        Book book = bookBiz.getById(bookId);
        //3.将对象保存到req
        req.setAttribute("book",book);
        //4.转发到 jsp页面
        req.getRequestDispatcher("book_details.jsp").forward(req,resp);
    }

    private void modify(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws Exception {

        //1.构建一个磁盘工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //1.1 设置大小
        factory.setSizeThreshold(1024*9);
        //1.2 临时仓库
        File file = new File("e:\\temporary");
        if(!file.exists()){
            file.mkdir();//创建文件夹
        }
        factory.setRepository(file);

        //2.文件上传+表单数据
        ServletFileUpload  fileUpload = new ServletFileUpload(factory);

        //3.将请求解析成一个个FileItem(文件+表单元素)
        List<FileItem> fileItems = fileUpload.parseRequest(req);

        //4.遍历FileItem
        Book book  =new Book();
        for(FileItem  item: fileItems){
            if(item.isFormField()){
                //4.1 元素名称和用户填写的值  name: 文城
                String  name = item.getFieldName();
                String value = item.getString("utf-8");//防止乱码
                switch(name){
                    case "id":
                        book.setId(Long.parseLong(value));
                        break;
                    case "pic":
                        book.setPic(value);
                        break;
                    case "typeId":
                        book.setTypeId(Long.parseLong(value));
                        break;
                    case "name":
                        book.setName(value);
                        break;
                    case "price":
                        book.setPrice(Float.parseFloat(value));
                        //book.setPrice(new Double(Double.parseDouble(value)*1.0).longValue());
                        break;
                    case "desc":
                        book.setDesc(value);
                        break;
                    case "publish":
                        book.setPublish(value);
                        break;
                    case "author":
                        book.setAuthor(value);
                        break;
                    case "stock":
                        book.setStock(Long.parseLong(value));
                        break;
                    case "address":
                        book.setAddress(value);
                        break;
                }

            }else {
                String fileName = item.getName();
                if(fileName.trim().length()>0) {
                    String path = req.getServletContext().getRealPath("/Images/cover");
                    String filePath = path + "/" + fileName;
                    //数据库表中的路径
                    String dbPath = "Images/cover/" + fileName;
                    book.setPic(dbPath);

                    //4.3 保存文件
                    item.write(new File(filePath));
                }
            }
        }

        //5.将信息保存到数据库
        int count = bookBiz.modify(book.getTypeId(),book.getName(),book.getPrice(),book.getDesc(),book.getPic(),book.getPublish(),book.getAuthor(),book.getStock(),book.getAddress(),book.getId());
        if(count>0){
            out.println("<script>alert('修改书籍成功');location.href='book?type=query&page=1';</script>");
        }else{
            out.println("<script>alert('修改书籍失败');location.href='book?type=query&page=1';</script>");
        }
    }
}
